package sistemioperativi.barbiere.es12;
import java.util.concurrent.*;

public class SaloneSemFIFO extends Salone{

	private Semaphore mutex = new Semaphore(1);
	private Semaphore barbiere = new Semaphore(0);
	
	private Semaphore clientiInAttesa = new Semaphore(0, true);
	private Semaphore clienteServito = new Semaphore(0);
	
	public SaloneSemFIFO(int capienza) {
		super(capienza);
		
	}

	@Override
	protected void getCliente() throws InterruptedException {
		mutex.acquire();
		if(numClientiInAttesa == 0){
			barbiereAddormentato = true;
			mutex.release();
			barbiere.acquire();
			barbiereAddormentato = false;
		} else {
	
			clientiInAttesa.release();
			barbiere.acquire();
			
		}
		
		mutex.release();
		
	}

	@Override
	protected void congedaCliente() throws InterruptedException {
		
		mutex.acquire();
		clienteServito.release();
		
		
	}

	@Override
	protected boolean entra() throws InterruptedException {
		
		boolean esito = true;
		mutex.acquire();
		
		if(barbiereAddormentato){
			siediInPoltrona();
		} else
			if(numClientiInAttesa < capienza){
				attendiInSalaDAttesa();
				siediInPoltrona();
			} else {
				esito = false;
			}
		
		mutex.release();
		
		return esito;
	}
	
	private void attendiInSalaDAttesa() throws InterruptedException {
		numClientiInAttesa++;
		mutex.release();
		clientiInAttesa.acquire();
		numClientiInAttesa--;
		
	}

	private void siediInPoltrona() throws InterruptedException{
	//	barbiereAddormentato = false;
		
		barbiere.release();
		clienteServito.acquire();
	}
	
}
